#include "note.h"

Note::Note(QString text)
    :m_text(text)
{
    m_datetime = QDateTime::currentDateTime();
}

Note::Note(int id, int taskId, QString text, QDateTime datetime)
    :m_id(id),
      m_taskId(taskId),
      m_text(text),
      m_datetime(datetime)
{

}



Notes::Notes(QTextEdit *note_edit, QPushButton *front_btn, QPushButton *next_btn, QPushButton *save_btn, QLabel *note_edit_time, QLabel *note_page, QObject *parent)
    :QObject(parent),
      m_index(-1),
      m_pnote_list(nullptr),
      m_pnote_edit(note_edit),
      m_front_btn(front_btn),
      m_next_btn(next_btn),
      m_note_edit_time(note_edit_time),
      m_save_btn(save_btn),
      m_note_page(note_page)
{
    if(m_pnote_edit != nullptr) QObject::connect(m_pnote_edit, &QTextEdit::textChanged, this , &Notes::textChanged_slot);
    if(m_front_btn != nullptr) QObject::connect(m_front_btn, &QPushButton::released, this , &Notes::frontClick_slot);
    if(m_next_btn != nullptr) QObject::connect(m_next_btn, &QPushButton::released, this , &Notes::nextClick_slot);
    if (m_save_btn != nullptr) QObject::connect(m_save_btn, &QPushButton::released, this , &Notes::saveClick_slot);

    // 按钮
    m_front_btn->setDisabled(true);
    m_next_btn->setDisabled(true);

}

bool Notes::getNotes(int taskId)
{
    if (m_pnote_list != nullptr) delete m_pnote_list;

    QString sql = QString("SELECT id, taskId, text, datetime FROM note WHERE taskId=%1 ORDER BY id").arg(taskId);
    if (!Ndb::query.exec(sql))
    {
        qDebug() << "taskId " << taskId << " note 获取失败";
        m_pnote_list = nullptr;
        return false;
    } else {
        m_pnote_list = new NoteList;
        while (Ndb::query.next())
        {
            m_pnote_list->push_back(Note(
                                    Ndb::query.value("id").toInt(),
                                    Ndb::query.value("taskId").toInt(),
                                    Ndb::query.value("text").toString(),
                                    Ndb::query.value("datetime").toDateTime()
                                    ));
        }
        if (m_pnote_list->size() >= 1)
        {
            m_index = 0;
            if (!m_pnote_list->at(m_index).m_text.isEmpty())    m_next_btn->setDisabled(false);
        } else {

            createNoteAndUpdateIndex(taskId);

        }



        m_note_page->setText(QString("%1/%2").arg(m_index+1).arg(m_pnote_list->size()));
        return true;
    }


}

void Notes::showNote()
{
    showNote(m_index);
}

void Notes::showNote(const Note &note)
{

    m_pnote_edit->setPlainText(note.m_text);
    m_note_edit_time->setText(QString("上次修改：%1").arg(note.m_datetime.toString("MM-dd HH:mm:ss")));
}

void Notes::showNote(int index)
{
    if (m_pnote_list->empty()) return;
    if (index < 0) index = 0;
    if (index >= m_pnote_list->size()) index = m_pnote_list->size() - 1;

    const Note &note = m_pnote_list->at(index);
    showNote(note);
}

bool Notes::setIndex(int index)
{
    bool flag = true;
    if (index < 0)
    {
        index = 0;
        flag = false;
    }

    if (index >= m_pnote_list->size())
    {
        index = m_pnote_list->size() - 1;
        flag = false;
    }

    m_index = index;

    m_note_page->setText(QString("%1/%2").arg(m_index+1).arg(m_pnote_list->size()));

    return flag;
}

bool Notes::addIndex()
{
    if (isLast()) return false;
    m_index++;

    m_note_page->setText(QString("%1/%2").arg(m_index+1).arg(m_pnote_list->size()));
    return true;
}

bool Notes::reduceIndex()
{
    if (m_index <= 0) return false;
    m_index--;

    m_note_page->setText(QString("%1/%2").arg(m_index+1).arg(m_pnote_list->size()));
    return true;
}

bool Notes::nextNote()
{
    if(!addIndex()) return false;
    showNote();
}

bool Notes::createNoteAndUpdateIndex(int taskId)
{
    m_pnote_list->push_back(Note("记录你的笔记。"));
    Note &note = m_pnote_list->last();
    if (m_pnote_list->size() > 1) note.m_text="";
    note.m_taskId = taskId;

    QString sql = "INSERT INTO note(taskId, text) VALUES(:taskId, :text);";
    Ndb::query.prepare(sql);
    Ndb::query.bindValue(":taskId", note.m_taskId);
    Ndb::query.bindValue(":text", note.m_text);

    if (Ndb::query.exec())
    {
        note.m_id = Ndb::getLastInsertId("note");
        m_index < 0?m_index = 0:addIndex();
        return true;
    }
    qDebug() << "Fail to create note "  << Ndb::query.lastError();
    m_note_edit_time->setText(QString("上次修改：%1").arg(QDateTime::currentDateTime().toString("MM-dd HH:mm:ss")));
    return false;


}

bool Notes::updateNote(Note &note)
{
    note.m_text = m_pnote_edit->toPlainText();

    QString sql = "UPDATE note SET text=:text, datetime=datetime('now', 'localtime') WHERE id=:id;";
    Ndb::query.prepare(sql);
    Ndb::query.bindValue(":id", note.m_id);
    Ndb::query.bindValue(":text", note.m_text);
    if(!Ndb::query.exec())
    {
        qDebug() << "update note failed id=" <<note.m_id << " " << Ndb::query.lastError() << "\n" << Ndb::query.lastQuery();
        return false;
    }
    m_note_edit_time->setText(QString("上次修改：%1").arg(QDateTime::currentDateTime().toString("MM-dd HH:mm:ss")));


    return true;
}

bool Notes::deleteNoteFromListIndex(int index)
{
    int id = m_pnote_list->at(index).m_id;

    QString sql = "DELETE FROM note WHERE id=:id";
    Ndb::query.prepare(sql);
    Ndb::query.bindValue(":id", id);

    if (!Ndb::query.exec())
    {
        qDebug() << "delete note error id=" << id;
        return false;
    }
    m_pnote_list->removeAt(index);

    return true;
}

void Notes::update(int taskId)
{
    m_taskId = taskId;
    getNotes(m_taskId);
    showNote();

}

void Notes::textChanged_slot()
{
    if (m_taskId < 0) return ;
    m_pnote_edit->toPlainText().isEmpty() && isLast()?m_next_btn->setDisabled(true):m_next_btn->setDisabled(false);
}



void Notes::frontClick_slot()
{
    if (m_index > 0)
    {
        // delete empty note
        if (m_pnote_edit->toPlainText().isEmpty())
        {
            deleteNoteFromListIndex(m_index);

        }
        else if (m_pnote_list->value(getIndex()).m_text != m_pnote_edit->toPlainText())
        {
            int ret = QMessageBox::information(nullptr, "提示", "是否保存当前笔记", "保存", "取消");
            if (ret == 0)
            {
                saveClick_slot();
            }

        }

        m_front_btn->setDisabled(false);
        reduceIndex();
        showNote();
        if (m_index <= 0) m_front_btn->setDisabled(true);
    }
    qDebug() << "current index " << m_index ;
}

void Notes::nextClick_slot()
{

    if (m_pnote_list->value(getIndex()).m_text != m_pnote_edit->toPlainText())
    {
        int ret = QMessageBox::information(nullptr, "提示", "是否保存当前笔记", "保存", "取消");
        if (ret == 0)
        {
            saveClick_slot();
        }

    }

    if (isLast())
    {
        createNoteAndUpdateIndex(m_taskId);
        showNote(getIndex());
    } else {
        addIndex();
        showNote(getIndex());
    }



    if (m_index != 0) m_front_btn->setDisabled(false);

    qDebug() << "current index " << m_index ;


}

void Notes::saveClick_slot()
{
    if (m_taskId < 0 ) return;
    Note &note = (*m_pnote_list)[getIndex()];
    note.m_text = m_pnote_edit->toPlainText();
    updateNote(note);

}
